package com.example.android.course.sample.helpers;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;

import android.nfc.FormatException;
import android.os.Environment;
import android.util.Log;

public class IOHelepr {

    private static final String DEFAULT_USERNAME = "user1";

    private static final String DEFAULT_PASSWORD = "password";

    private static final String CREDENTIALS_FILE_NAME = "credFile";

    private String storedUsername;
    private String storedPassword;

    private static final String LOG_TAG = "IOHelepr";

    public boolean areCredentialsCorrect(String username, String password) {
        readUsernameAndPasswordFromExternalFile(CREDENTIALS_FILE_NAME);
        return storedUsername.equals(username) && storedPassword.equals(password);
    }

    private void readUsernameAndPasswordFromExternalFile(String fileName) {

        String externalStoragePath = Environment.getExternalStorageDirectory().getAbsolutePath();
        File file = createAuthFileIfNotExists(externalStoragePath, fileName);

        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String line = null;
            while ((line = reader.readLine()) != null) {
                processAuthFileLine(line);
            }

        } catch (FileNotFoundException e) {
            Log.w(LOG_TAG, e);
        } catch (IOException e) {
            Log.w(LOG_TAG, e);
        } catch (FormatException e) {
            Log.w(LOG_TAG, e);
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                Log.w(LOG_TAG, e);
            }
        }
    }

    private void processAuthFileLine(String line) throws FormatException {
        String[] resultArr = line.trim().split("\\s*[:]\\s*");
        if (resultArr.length != 2) {
            throw new FormatException("The line is not in the correct format: " + line);
        }

        String key = resultArr[0].toLowerCase().trim();
        String value = resultArr[1].trim();

        if (key.equals("username")) {
            this.storedUsername = value;
        } else if (key.equals("password")) {
            this.storedPassword = value;
        } else {
            throw new FormatException("The line is not in the correct format: " + line);
        }
    }

    private File createAuthFileIfNotExists(String filePath, String fileName) {
        File file = new File(filePath, fileName);
        if (!file.exists() || file.isDirectory()) {
            Writer writer = null;

            String newLine = System.getProperty("line.separator");
            try {

                FileOutputStream os = new FileOutputStream(file);

                writer = new BufferedWriter(new OutputStreamWriter(os, "utf-8"));
                writer.write(String.format("%s%s", "Username : " + DEFAULT_USERNAME, newLine));
                writer.write(String.format("%s%s", "Password:" + DEFAULT_PASSWORD, newLine));

            } catch (IOException ex) {
                Log.w(LOG_TAG, ex);
            } finally {
                try {
                    if (writer != null) {
                        writer.close();
                    }
                } catch (Exception ex) {
                    Log.w(LOG_TAG, ex);
                }
            }
        }

        return file;
    }

}
